<!--
 * @Author: MuQuanyu(MQy)
 * @Date: 2025-10-14 14:25:45
 * @LastEditTime: 2025-10-24 16:01:49
 * @email: muquanyu@outlook.com
-->
<template>
  <div class="menu-manager-box">
    <el-drawer class="custom-rtl-drawer" :before-close="closeMenuDrawer" size="500px" v-model="menuAddOrEditDrawerVis"
      :title="isMenuAdd ? '添加菜单' : '编辑菜单'" direction="rtl">
      <div class="drawer-content-box">
        <div class="drawer-main-box-outer">
          <div class="drawer-main-box">
            <el-form v-loading="isMenuFormLoading" :model="menuForm" ref="menuFormRef" :rules="menuFormRules"
              label-width="auto">
              <el-row justify="space-between">
                <el-col :span="24">
                  <el-form-item label="上级菜单" prop="parentId">
                    <el-cascader popper-class="loading" v-model="parentMenuData" :props="{
                      value: 'id',
                      label: 'title',
                      checkStrictly: true
                    }" :options="tableData" @change="parentMenuChange" @visible-change="parentMenuVisChange"
                      placeholder="请选择（默认顶级）" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="菜单标题" prop="title">
                    <el-input v-model="menuForm.title"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="菜单类型" prop="type">
                    <el-radio-group v-model="menuForm.type">
                      <el-radio-button label="目录" :value="0" />
                      <el-radio-button label="菜单" :value="1" />
                    </el-radio-group>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="路由名称" prop="name">
                    <el-input v-model="menuForm.name"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="路由路径" prop="path">
                    <el-input v-model="menuForm.path"></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="组件路径" prop="component">
                    <el-input :disabled="menuForm.type == 0" v-model="menuForm.component" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="重定向" prop="redirect">
                    <el-input v-model="menuForm.redirect"></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="菜单图标" prop="icon">
                    <icon-picker @handle-click-icon="clickIcon">
                      <el-button>
                        <i :class="menuForm.icon" v-if="menuForm.icon"></i>
                        <span v-else>选择图标</span>
                      </el-button>
                    </icon-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否隐藏" prop="hidden">
                    <el-radio-group v-model="menuForm.hidden">
                      <el-radio label="是" :value="true" />
                      <el-radio label="否" :value="false" />
                    </el-radio-group>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="是否缓存" prop="icon">
                    <el-radio-group v-model="menuForm.keepAlive">
                      <el-radio label="是" :value="true" />
                      <el-radio label="否" :value="false" />
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="排序权值" prop="hidden">
                    <el-input type="number" v-model="menuForm.sort"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

        </div>
        <div class="drawer-bottom-box">
          <div class="dbb-box">
            <el-button type="primary" :disabled="isMenuFormLoading" @click="submitAddOrEditMenu">提交</el-button>
          </div>
        </div>
      </div>


    </el-drawer>
    <el-drawer class="custom-rtl-drawer" :before-close="closeBtnAuthDrawer" size="500px" v-model="btnAuthDrawerVis"
      title="按钮权限" direction="rtl">
      <div class="drawer-content-box">
        <div class="drawer-main-box-outer">
          <div class="drawer-main-box">
            <el-button type="primary" style="margin-bottom: 20px;" @click="showAddBtnAuthDialog">新增按钮权限</el-button>
            <el-button type="danger" style="margin-bottom: 20px;" @click="deleteBtnAuths">批量删除</el-button>
            <el-table border height="calc(100vh - 190px)" v-loading="isBtnAuthTableLoading"
              :header-cell-style="{ background: 'var(--yu-div-hover-gray)', color: 'var(--yu-text-color)' }"
              :data="currentBtnAuthList" :tree-props="{
                checkStrictly: false
              }" row-key="id" @selection-change="handleSelectionBtnAuthChange">
              <template #empty>
                <div style="display: flex; flex-direction: column; gap: 10px; align-items: center">
                  <i class="iconfont icon-kongshuju" style="font-size: 100px"></i>
                  <span>空数据</span>
                </div>
              </template>
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="权限名称" />
              <el-table-column prop="permission" label="权限码" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button link type="primary" @click="showEditBtnAuthDialog(scope.row.id)">修改</el-button>
                  <DeletePopconfirm @handle-delete="deleteBtnAuthSingle" :row-data="scope.row"
                    :loading="isDeleteBtnAuthSingleLoading">
                    <el-button link type="danger">删除</el-button>
                  </DeletePopconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>
        <!-- <div class="drawer-bottom-box">
          <div class="dbb-box">
            <el-button type="primary" :disabled="isMenuFormLoading">提交</el-button>
          </div>
        </div> -->
        <div class="custom-pagination-box" style="margin-top: -15px;">
          <el-pagination v-model:current-page="btnAuthPageObj.page" v-model:page-size="btnAuthPageObj.pageSize"
            :page-sizes="[10, 20, 30, 40]" :size="'default'" :disabled="false" :background="false"
            layout="total, sizes, prev, pager, next, jumper" :total="btnAuthPageObj.total"
            @size-change="handleBtnAuthSizeChange" @current-change="handleBtnAuthCurrentChange" />
        </div>
      </div>
      <el-dialog class="custom-dialog" v-model="btnAuthDialogVis" :title="isBtnAuthEdit ? '编辑按钮权限' : '添加按钮权限'"
        :before-close="btnAuthDialogClose">
        <el-form v-loading="isBtnAuthDialogLoading" style="padding: 15px" ref="btnAuthDialogFormRef"
          :model="btnAuthForm" :rules="btnAuthFormRules" label-width="auto">
          <el-row justify="space-between">
            <el-col>
              <el-form-item label="权限名" prop="name">
                <el-input v-model="btnAuthForm.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="space-between">
            <el-col>
              <el-form-item label="权限码" prop="permission">
                <el-input v-model="btnAuthForm.permission"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="space-between">
            <el-col>
              <el-form-item label="排序权值" prop="sort">
                <el-input v-model="btnAuthForm.sort"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="dialog-bottom" style="display: flex; align-items: center; justify-content: flex-end">
          <el-button :disabled="isBtnAuthDialogLoading" @click="btnAuthDialogClose">取消</el-button>
          <el-button :disabled="isBtnAuthDialogLoading" type="primary" @click="btnAuthDialogConfirm">确定</el-button>
        </div>
      </el-dialog>

    </el-drawer>
    <el-card class="card-box">
      <div class="btn-box">
        <el-button type="primary" @click="showAddMenuDrawer">添加</el-button>
        <el-button type="danger" @click="deleteMenus">批量删除</el-button>
      </div>
      <el-table border height="calc(100vh - 220px)" :header-cell-style="{
        textAlign: 'center',
        background: 'var(--yu-div-hover-gray)',
        color: 'var(--yu-text-color)'
      }" :data="tableData" :tree-props="{
        checkStrictly: false
      }" :default-expand-all="true" row-key="id" @selection-change="handleSelectionMenuChange">
        <template #empty>
          <div style="display: flex; flex-direction: column; gap: 10px; align-items: center">
            <i class="iconfont icon-kongshuju" style="font-size: 100px"></i>
            <span>空数据</span>
          </div>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column label="菜单名称">
          <template #default="scope">{{ scope.row.meta.title ? scope.row.meta.title : scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="类型" width="70px" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.meta.type == 0" type="danger">目录</el-tag>
            <el-tag v-if="scope.row.meta.type == 1" type="primary">菜单</el-tag>
          </template>

        </el-table-column>
        <el-table-column label="图标" width="60px" align="center">
          <template #default="scope">
            <i style="font-size: 18px;" :class="scope.row?.meta?.icon"></i>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由地址" />
        <el-table-column prop="meta.fullPath" label="完整路由地址" />
        <el-table-column prop="meta.component" label="组件地址" />
        <el-table-column label="隐藏" width="60px" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.meta.hidden" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="meta.sort" label="排序" width="60px" align="center" />
        <el-table-column label="操作">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center;">
              <el-button type="primary" link @click="showEditMenuDrawer(scope.row)">编辑</el-button>
              <DeletePopconfirm @handle-delete="deleteMenuSingle" :row-data="scope.row"
                :loading="isDeleteMenuSingleLoading">
              </DeletePopconfirm>

              <el-button type="primary" v-if="scope.row.meta?.type == 1" @click="showBtnAuthDrawer(scope.row.id)"
                link>按钮权限</el-button>
            </div>
          </template>

        </el-table-column>
      </el-table>
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { useAuthStore } from '@/store';
import { onMounted, reactive, ref, watch } from 'vue';
import IconPicker from '@/components/IconPicker/index.vue'
import { ElMessage, ElMessageBox, type FormRules } from 'element-plus';
import { AddSysRoute, DeleteSysRoute, EditSysRoute, SysRouteDetail, SysRoutePage } from '@/api/sys/route';
import { GetSysRouteTree } from '@/api/sys/user';
import DeletePopconfirm from '@/components/DeletePopconfirm/index.vue'
import { buildRoutesFromServer, extractKeepAliveList } from '@/utils/route';
import router from '@/router';

const tableData: any = ref([])
const parentMenuData = ref<any>([])
const menuFormRef = ref()
const authStore = useAuthStore()
const menuAddOrEditDrawerVis = ref(false)
const isMenuAdd = ref(true) // 是否为添加菜单/目录
const isMenuFormLoading = ref(false) // 菜单抽屉loading
interface MenuForm {
  parentId: string // 上级菜单
  type: number // 0 目录 1 菜单 2 按钮
  title: string // 菜单标题
  name: string // 路由名称
  path: string // 路由路径
  component: string // 组件路径
  redirect: string // 重定向 url
  requireAuth: boolean // 是否需要登录才能访问
  iconType: string // 图标类型
  icon: string // 图标 class 名
  hidden: boolean // 是否隐藏
  keepAlive: boolean // 是否缓存
  sort: number // 排序权值
}
const menuForm = ref<MenuForm>({
  parentId: '0', // 上级菜单
  type: 0, // 0 目录 1 菜单 2 按钮
  title: '', // 菜单标题
  name: '', // 路由名称
  path: '', // 路由路径
  component: '', // 组件路径
  redirect: '', // 重定向 url
  requireAuth: true, // 是否需要登录才能访问
  iconType: '', // 图标类型
  icon: '', // 图标 class 名
  hidden: false, // 是否隐藏
  keepAlive: false, // 是否缓存
  sort: 0 // 排序权值
})
const currentMenuId = ref<string | null>() // 当前菜单/目录 ID
const parentMenuChange = (e: any) => {
  if (e && e.length > 0) {
    menuForm.value.parentId = e[e.length - 1]
  } else {
    menuForm.value.parentId = "0"
  }
}
const parentMenuVisChange = async (isShow: any) => {
  if (isShow) {
    // let options = {
    //   target: '.loading',
    //   lock: true,
    //   text: "加载中..."
    // }
    // orgCascaderLoading.value = ElLoading.service(options)

    // orgCascaderLoading.value.close();
  }
}
const menuFormRules = reactive<FormRules<MenuForm>>({
  title: [{ required: true, message: "菜单标题必填", trigger: "blur" }],
  name: [{ required: true, message: "路由名称必填", trigger: "blur" }],
  path: [{ required: true, message: "访问url必填", trigger: "blur" }],
});

const showAddMenuDrawer = () => {
  isMenuAdd.value = true;
  menuAddOrEditDrawerVis.value = true;
}
const deleteMenus = async () => {
  if (selectedMenuItems.value.length > 0) {
    ElMessageBox.confirm(
      '确认删除么?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        const selectedIds = selectedMenuItems.value.map((x: any) => x.id)
        let res = await DeleteSysRoute({
          ids: selectedIds
        })
        if (res.code == 200) {
          ElMessage.success("批量删除成功")
          await refreshMenuList()
        }
      })
      .catch(() => {
      })
  } else {
    ElMessage.warning("请至少选择一项")
  }
}
const selectedMenuItems = ref<any>([])
const handleSelectionMenuChange = (e: any) => {
  selectedMenuItems.value = e
}
const showEditMenuDrawer = async (item: any) => {
  isMenuAdd.value = false;
  currentMenuId.value = item.id;
  isMenuFormLoading.value = true; // 加载
  menuAddOrEditDrawerVis.value = true;
  await sysRouteDetail()
  isFindFlag.value = false;
  parentIdPos.value = 0;
  parentMenuData.value = []


  if (item.parentId) {
    findParentIdArr(tableData.value, item.parentId)
    const tempList = []
    for (let i = 0; i <= parentIdPos.value; ++i) {
      tempList.push(parentMenuData.value[i]);
    }
    parentMenuData.value = tempList;
  }

  isMenuFormLoading.value = false

}
const closeMenuDrawer = () => {
  menuFormRef.value?.resetFields();
  menuForm.value = {
    parentId: '0', // 上级菜单
    type: 0, // 0 目录 1 菜单 2 按钮
    title: '', // 菜单标题
    name: '', // 路由名称
    path: '', // 路由路径
    component: '', // 组件路径
    redirect: '', // 重定向 url
    requireAuth: true, // 是否需要登录才能访问
    iconType: '', // 图标类型
    icon: '', // 图标 class 名
    hidden: false, // 是否隐藏
    keepAlive: false, // 是否缓存
    sort: 0 // 排序权值
  }
  parentMenuData.value = []
  menuAddOrEditDrawerVis.value = false;
}
const initTableData = (data: any, parentId: any) => {
  for (let i = 0; i < data.length; ++i) {
    data[i].id = data[i].meta?.id
    data[i].id = data[i].meta?.id
    data[i].parentId = parentId
    data[i].title = data[i].meta?.title ? data[i].meta?.title : data[i].name
    data[i].title += data[i].children ? "(" + data[i].children.length + ")" : ''
    initTableData(data[i].children ? data[i].children : [], data[i].id)
  }
}
const clickIcon = (icon: any) => {
  if (menuForm.value.icon == icon) {
    menuForm.value.iconType = ""
    menuForm.value.icon = ""
  } else {
    menuForm.value.iconType = "fontawesome"
    menuForm.value.icon = icon
  }

}
watch(
  () => menuForm.value.type,
  (newVal) => {
    if (newVal == 0) {
      menuForm.value.component = ""
    }
  }
);
const submitAddOrEditMenu = async () => {
  if (isMenuAdd.value) {
    // 添加

    let res = await AddSysRoute({
      parentId: menuForm.value.parentId,
      type: menuForm.value.type, // 0 目录 1 菜单 2 按钮
      title: menuForm.value.title, // 菜单标题
      name: menuForm.value.name, // 路由名称
      path: menuForm.value.path, // 路由路径
      component: menuForm.value.component, // 组件路径
      extMeta: { redirect: menuForm.value.redirect }, // 重定向 url
      requireAuth: true, // 是否需要登录才能访问
      iconType: menuForm.value.iconType, // 图标类型
      icon: menuForm.value.icon, // 图标 class 名
      hidden: menuForm.value.hidden, // 是否隐藏
      keepAlive: menuForm.value.keepAlive, // 是否缓存
      sort: menuForm.value.sort.toString() // 排序权值
    })
    if (res.code == 200) {
      ElMessage.success("添加成功")

    }
  } else {
    let res = await EditSysRoute({
      id: currentMenuId.value,
      parentId: menuForm.value.parentId,
      type: menuForm.value.type, // 0 目录 1 菜单 2 按钮
      title: menuForm.value.title, // 菜单标题
      name: menuForm.value.name, // 路由名称
      path: menuForm.value.path, // 路由路径
      component: menuForm.value.component, // 组件路径
      extMeta: { redirect: menuForm.value.redirect }, // 重定向 url
      requireAuth: true, // 是否需要登录才能访问
      iconType: menuForm.value.iconType, // 图标类型
      icon: menuForm.value.icon, // 图标 class 名
      hidden: menuForm.value.hidden, // 是否隐藏
      keepAlive: menuForm.value.keepAlive, // 是否缓存
      sort: menuForm.value.sort // 排序权值
    })
    if (res.code == 200) {
      ElMessage.success("编辑成功")
    }
  }
  await refreshMenuList()
  closeMenuDrawer()
}
const refreshMenuList = async () => {
  const res = await GetSysRouteTree();

  if (res.code === 200) {
    const asyncRoutes = buildRoutesFromServer(res.data as any);
    authStore.setDynamicRoutes(asyncRoutes);
    // console.log("dynamicRoutes => ", authStore.dynamicRoutes);
    const keepAliveList = extractKeepAliveList(asyncRoutes);

    authStore.setKeepAliveList(keepAliveList);
    // console.log("keepAliveList => ", authStore.keepAliveList);
    router.clearRoutes();
    asyncRoutes.forEach((route) => {

      router.addRoute(route); // 动态添加路由
    });
    router.addRoute({
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/views/Other/404.vue"),
    });

    router.addRoute({
      path: "/",
      redirect: router.getRoutes()[0].path,
    });

  }
  tableData.value = removeType2Menus(authStore.dynamicRoutes)

  initTableData(tableData.value, null)
}
const sysRouteDetail = async () => {
  let res = await SysRouteDetail({
    id: currentMenuId.value
  })
  if (res.code == 200) {
    menuForm.value = {
      parentId: res.data.parentId, // 上级菜单
      type: res.data.type, // 0 目录 1 菜单 2 按钮
      title: res.data.title, // 菜单标题
      name: res.data.name, // 路由名称
      path: res.data.path, // 路由路径
      component: res.data.component, // 组件路径
      redirect: res.data.extMeta?.redirect ? res.data.extMeta.redirect : '', // 重定向 url
      requireAuth: res.data.requireAuth, // 是否需要登录才能访问
      iconType: res.data.iconType, // 图标类型
      icon: res.data.icon, // 图标 class 名
      hidden: res.data.hidden, // 是否隐藏
      keepAlive: res.data.keepAlive, // 是否缓存
      sort: res.data.sort // 排序权值
    }
  }
}

const isFindFlag = ref(false)
const parentIdPos = ref(0)
const findParentIdArr = (data: any, id: string) => {
  if (isFindFlag.value) return;
  for (let i = 0; i < data.length; ++i) {
    parentMenuData.value[parentIdPos.value] = data[i].id
    if (data[i].id == id) {
      isFindFlag.value = true;
      return;
    }
    parentIdPos.value++
    if (data[i]?.children) {
      findParentIdArr(data[i].children, id)
    }
    if (isFindFlag.value) return;
    parentIdPos.value--;
  }


}
const isDeleteMenuSingleLoading = ref(false)
const deleteMenuSingle = async (e: any) => {
  isDeleteMenuSingleLoading.value = true
  let res = await DeleteSysRoute({
    ids: [e.id]
  })
  if (res.code == 200) {
    ElMessage.success("删除成功")
  }
  await refreshMenuList()
  isDeleteMenuSingleLoading.value = false
}
//#region @按钮权限
const btnAuthDrawerVis = ref(false)
const currentBtnAuthList = ref([])
const btnAuthDialogVis = ref(false)
const isBtnAuthEdit = ref(false)
const isBtnAuthDialogLoading = ref(false)
interface BtnAuthForm {
  name: string
  permission: string
  sort: number
}
const currentBtnAuthId = ref<string | null>()
const btnAuthForm = ref<BtnAuthForm>({
  name: '',
  permission: '',
  sort: 0
})
const btnAuthFormRules = reactive<FormRules<BtnAuthForm>>({
  name: [{ required: true, message: "权限名必填", trigger: "blur" }],
  permission: [{ required: true, message: "权限码必填", trigger: "blur" }],
});
const btnAuthPageObj = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})
const showAddBtnAuthDialog = () => {
  isBtnAuthEdit.value = false; // 新增按钮权限
  btnAuthDialogVis.value = true;
}
const selectedBtnAuthItems = ref<any>([])
const handleSelectionBtnAuthChange = async (e: any) => {
  selectedBtnAuthItems.value = e
  console.log("selectedBtnAuthItems", selectedBtnAuthItems.value)
}
const deleteBtnAuths = async () => {
  if (selectedBtnAuthItems.value.length > 0) {
    ElMessageBox.confirm(
      '确认删除么?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        const selectedIds = selectedBtnAuthItems.value.map((x: any) => x.id)
        let res = await DeleteSysRoute({
          ids: selectedIds
        })
        if (res.code == 200) {
          ElMessage.success("批量删除成功")
          await initBtnAuthTableData(currentMenuId.value)
        }
      })
      .catch(() => {
      })
  } else {
    ElMessage.warning("请至少选择一项")
  }


}
const showEditBtnAuthDialog = async (id: string) => {
  currentBtnAuthId.value = id;
  isBtnAuthEdit.value = true;
  btnAuthDialogVis.value = true;
  isBtnAuthDialogLoading.value = true;
  let res = await SysRouteDetail({
    id
  });
  if (res.code == 200) {
    btnAuthForm.value = {
      name: res.data.name,
      permission: res.data.permission,
      sort: res.data.sort
    }
  }
  isBtnAuthDialogLoading.value = false;
}
const isBtnAuthTableLoading = ref(false)
const initBtnAuthTableData = async (id: any) => {
  isBtnAuthTableLoading.value = true;
  let res = await SysRoutePage({
    page: btnAuthPageObj.value.page,
    pageSize: btnAuthPageObj.value.pageSize,
    parentID: id
  })
  if (res.code == 200) {
    currentBtnAuthList.value = res.data.list
    console.log("按钮权限 => ", res.data)
  }
  btnAuthPageObj.value.total = res.data.total
  btnAuthPageObj.value.pages = res.data.pages
  isBtnAuthTableLoading.value = false;
}
const showBtnAuthDrawer = async (id: string) => {
  btnAuthDrawerVis.value = true;
  currentMenuId.value = id;
  await initBtnAuthTableData(currentMenuId.value)
}
const closeBtnAuthDrawer = () => {
  btnAuthDrawerVis.value = false;
}
const btnAuthDialogClose = () => {
  btnAuthDialogVis.value = false
}
// 分页组件
const handleBtnAuthSizeChange = async (e: any) => {
  btnAuthPageObj.value.pageSize = e
  await initBtnAuthTableData(currentMenuId.value)
}
const handleBtnAuthCurrentChange = async (e: any) => {
  btnAuthPageObj.value.page = e
  await initBtnAuthTableData(currentMenuId.value)
}
const btnAuthDialogConfirm = async () => {
  if (!isBtnAuthEdit.value) {
    // 增加
    let res = await AddSysRoute({
      parentId: currentMenuId.value,
      name: btnAuthForm.value.name,
      permission: btnAuthForm.value.permission,
      sort: btnAuthForm.value.sort.toString(),
    })
    if (res.code == 200) {
      ElMessage.success("新增成功")
    }
  } else {
    // 编辑
    let res = await EditSysRoute({
      id: currentBtnAuthId.value,
      name: btnAuthForm.value.name,
      permission: btnAuthForm.value.permission,
      sort: btnAuthForm.value.sort.toString(),
      parentId: currentMenuId.value,
    })
    if (res.code == 200) {
      ElMessage.success("编辑成功")
    }
  }
  btnAuthDialogVis.value = false;
  await initBtnAuthTableData(currentMenuId.value)
}
const isDeleteBtnAuthSingleLoading = ref(false)
const deleteBtnAuthSingle = async (e: any) => {
  isDeleteBtnAuthSingleLoading.value = true;
  let res = await DeleteSysRoute({
    ids: [e.id]
  })
  if (res.code == 200) {
    ElMessage.success("按钮权限删除成功")
  }
  isDeleteBtnAuthSingleLoading.value = false;
  await initBtnAuthTableData(currentMenuId.value)
}
function removeType2Menus(menus: any) {
  return menus
    .filter((item: any) => item.meta.type !== 2) // 过滤掉 type = 2 的
    .map((item: any) => ({
      ...item,
      children: item.children ? removeType2Menus(item.children) : []
    }));
}

//#endregion
onMounted(async () => {
  tableData.value = removeType2Menus(authStore.dynamicRoutes)
  initTableData(tableData.value, null)

})
</script>

<style lang="scss" scoped>
.menu-manager-box {
  height: 100%;

  .card-box {
    height: 100%;

    ::v-deep(.el-card__body) {
      display: flex;
      flex-direction: column;
    }

    .btn-box {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }

  }
}

.drawer-content-box {
  display: flex;
  flex-direction: column;
  height: 100%;

  .drawer-main-box-outer {
    height: calc(100vh - 100px);
    overflow-y: auto;

    .drawer-main-box {
      padding: 15px;
    }
  }

}

.drawer-bottom-box {
  border-top: 1px solid var(--el-border-color);
  height: 50px;

  .dbb-box {
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
